import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Layout, Menu, Typography, message } from 'antd';
import { UserOutlined, LogoutOutlined, FileImageOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getAllCustomers } from '../api/adminApi';

const { Header, Content, Footer } = Layout;
const { Title } = Typography;

const MerchantCustomerList = () => {
  const [customers, setCustomers] = useState([]);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 检查登录状态
  useEffect(() => {
    const token = localStorage.getItem('token');
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    
    if (!token || user.role !== 'merchant') {
      message.error('请先登录商家账号');
      navigate('/login');
      return;
    }
    
    fetchCustomers();
  }, [navigate]);

  // 获取客户列表
  const fetchCustomers = async () => {
    setLoading(true);
    try {
      const data = await getAllCustomers();
      if (Array.isArray(data)) {
        setCustomers(data);
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
      message.error('获取客户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
    message.success('已退出登录');
  };

  // 查看客户照片
  const handleViewCustomer = (customerId) => {
    navigate(`/merchant/customer/${customerId}`);
  };

  // 返回照片管理
  const navigateToHome = () => {
    navigate('/merchant');
  };

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '照片数量',
      dataIndex: 'photoCount',
      key: 'photoCount',
      render: (count) => count || 0,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" onClick={() => handleViewCustomer(record._id)}>
          查看照片
        </Button>
      ),
    },
  ];

  return (
    <Layout className="layout" style={{ minHeight: '100vh' }}>
      <Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div className="logo">
          <Title level={4} style={{ color: 'white', margin: 0 }}>YYB照片打印系统</Title>
        </div>
        <Menu theme="dark" mode="horizontal" selectedKeys={['customers']}>
          <Menu.Item key="photos" icon={<FileImageOutlined />} onClick={navigateToHome}>
            照片管理
          </Menu.Item>
          <Menu.Item key="customers" icon={<UserOutlined />}>
            客户管理
          </Menu.Item>
          <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
            退出登录
          </Menu.Item>
        </Menu>
      </Header>
      
      <Content style={{ padding: '50px' }}>
        <Card title="客户列表">
          <Table
            rowKey="_id"
            columns={columns}
            dataSource={customers}
            loading={loading}
            pagination={{ pageSize: 10 }}
          />
        </Card>
      </Content>
      
      <Footer style={{ textAlign: 'center' }}>
        YYB照片打印系统 ©{new Date().getFullYear()} 商家端
      </Footer>
    </Layout>
  );
};

export default MerchantCustomerList; 